#include "client.h"
#include <stdio.h>

client::client()
{
		// opens the message queue
		messQ = OpenMessageQ(KEY_MSG);
		if (messQ == INVALID_HANDLE){
			printf("Eroare la deschidere Mailslot");
			exit(1);
		}
		// opens semaphores
		sem = OpenSem(KEY_SEM);
		if (sem == INVALID_HANDLE){
			printf("Eroare la deschidere sem1");
			exit(1);
		}
		semOp = OpenSem(KEY_SEM2);
		if (semOp == INVALID_HANDLE){
			printf("Eroare la deschidere dem2");
			exit(1);
		}
		// opens shared memory
		sh = OpenSharedMemory(KEY_SHM);
		if (sh == INVALID_HANDLE){
			printf("Eroare la deschidere memorie partajata");
			exit(1);
		}
}


client::~client()
{
		// close all Handles
		CloseMessageQueue(messQ);
		CloseSem(sem);
		CloseSem(semOp);
		CloseSharedMemory(sh);

}


void client::run(int arc, char* commandLine[])
{
	tMsg message;	// the message which is sent to the client
	BOOL bRes;
	int val;
	int i = 1;
	
	// parse the command line
	while (i<arc)
	{
		//  ADD command
		if (strcmp(commandLine[i],"a") == 0){
			i++;
			val = atoi(commandLine[i]);
			message.type = MSG_ADD;
			message.value = val;
			bRes = SendMessageQueue(messQ,&message);
		}
		//  CLEAR command
		else if (strcmp(commandLine[i],"c") == 0){
			message.type = MSG_CLEAR;
			SendMessageQueue(messQ,&message);
			
		}
		// SLEEP command
		else if (strcmp(commandLine[i],"s") == 0){
				i++;
				val = atoi(commandLine[i]);
				SleepEx(val*2,FALSE);
		}
		// REMOVE command
		else if (strcmp(commandLine[i],"r") == 0){
				i++;
				val = atoi(commandLine[i]);
				message.type = MSG_REMOVE;
				message.value = val;
				SendMessageQueue(messQ,&message);
				
		}
		// EXIT command
		else if (strcmp(commandLine[i],"e") == 0){
				message.type = MSG_EXIT;	
				SendMessageQueue(messQ,&message);
		
		}
		// PRINT command
		else if (strcmp(commandLine[i],"p") == 0){

				message.type = MSG_PRINT;	
				SendMessageQueue(messQ,&message);
				
				AcquireSem(semOp); 
				// critical zone
				AcquireSem(sem);
				Node *varb = (Node*)AttachSharedMemory(sh);
				if (varb == NULL){// error
					printf("Eroare a MapViewOfFILe");
					exit(1);
				}
				bt.cloneArb(varb);	// copies form the shared memory in the local memory
				DetachSharedMemory(varb);
				ReleaseSem(sem);
				bt.printTree(0);	// print tree
				delete[] bt.arb;	// free memory

		}
		i++;

	}

}
int main(int argc, char* argv[])
{
	client c;
	c.run(argc,argv);
}